﻿<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script src="js/jquery.js"></script>
    <script src="js/listbox.js"></script>
    <script src="js/jquery-ui.min.js"></script>
    <link href="css/map-setting.css" rel="stylesheet" />
    <link href="css/listbox.css" rel="stylesheet" />
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
    <title></title>
    <style>
        .controls {
            margin-top: 16px;
            border: 1px solid transparent;
            border-radius: 2px 0 0 2px;
            box-sizing: border-box;
            -moz-box-sizing: border-box;
            height: 32px;
            outline: none;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        }

        #pac-input {
            background-color: #fff;
            padding: 0 11px 0 13px;
            width: 400px;
            font-family: Roboto;
            font-size: 15px;
            font-weight: 300;
            text-overflow: ellipsis;
        }

            #pac-input:focus {
                border-color: #4d90fe;
                margin-left: -1px;
                padding-left: 14px; /* Regular padding-left + 1. */
                width: 401px;
            }

        .pac-container {
            font-family: Roboto;
        }

        #type-selector {
            color: #fff;
            background-color: #4d90fe;
            padding: 5px 11px 0px 11px;
        }

            #type-selector label {
                font-family: Roboto;
                font-size: 13px;
                font-weight: 300;
            }

        #map-marker {
            width: 15%;
        }
    </style>

</head>
<body>


    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map_marker">
        <ul id="markers_list"></ul>
    </div>
    <div id="google_map"></div>

</body>
</html>

<script type="text/javascript">

    jQuery(document).ready(function () {
        var mapCenter = new google.maps.LatLng(47.6145, -122.3418); //Google map Coordinates
        var map;
        map_initialize(); // load map

        var editBtn;
        var removeBtn;
        var saveBtn;
        var contentString;
        var mapID;

        function map_initialize() {

            var MapTitle = "Add New Marker";
            var MapDesc;

            //Google map option
            var googleMapOptions =
            {
                center: mapCenter, // map center
                zoom: 17, //zoom level, 0 = earth view to higher value
                panControl: true, //enable pan Control
                zoomControl: true, //enable zoom control
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL //zoom control size
                },
                scaleControl: true, // enable scale control
                mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
            };
            map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);

            loadMarker();

            //##### drop a new marker on right click ######
            google.maps.event.addListener(map, 'rightclick', function (event) {
                var EditForm = '<p><div class="marker-edit">' +
                      '<form action="null" method="POST" name="SaveMarker" id="SaveMarker">' +
                      '<label for="pName"><span>Place Name :</span><input type="text" name="pName" class="save-name" placeholder="Enter Title" maxlength="40" /></label>' +
                      '<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc" placeholder="Enter Address" maxlength="150"></textarea></label>' +
                      '<label for="pType"><span>Type :</span> <select name="pType" class="save-type"><option value="modelTown">MODEL TOWN</option><option value="dha">DHA</option>' +
                      '<option value="gardenTown">Garden Town</option></select></label>' +
                      '</form>' +
                      '</div></p><button name="save-marker" class="save-marker">Save Marker Details</button>';

                if (mapID < 0) {
                    mapID = 1;
                }
                else {
                    mapID = mapID + 1;
                }
                addMarker(event.latLng, mapID, MapTitle, EditForm, false, true, true, "../Google Maps/css/images/pin_green.png");
            });


            //############### Search Box Functionality ##############
            var input = document.getElementById('pac-input');
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

            var searchBox = new google.maps.places.SearchBox((input));
            // [START region_getplaces]
            // Listen for the event fired when the user selects an item from the
            // pick list. Retrieve the matching places for that item.
            google.maps.event.addListener(searchBox, 'places_changed', function () {
                var places = searchBox.getPlaces();

                if (places.length == 0) {
                    return;
                }

                // For each place, get the icon, place name, and location.
                markers = [];
                var bounds = new google.maps.LatLngBounds();
                for (var i = 0, place; place = places[i]; i++) {
                    var image = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25)
                    };

                    // Create a marker for each place.
                    var marker = new google.maps.Marker({
                        map: map,
                        icon: image,
                        title: place.name,
                        position: place.geometry.location
                    });

                    markers.push(marker);
                    bounds.extend(place.geometry.location);
                }

                google.maps.event.addListener(map, 'zoom_changed', function () {
                    zoomChangeBoundsListener =
                        google.maps.event.addListenerOnce(map, 'bounds_changed', function (event) {
                            if (this.getZoom() > 15 && this.initialZoom == true) {
                                // Change max/min zoom here
                                this.setZoom(18);
                                this.initialZoom = false;
                            }
                            google.maps.event.removeListener(zoomChangeBoundsListener);
                        });
                });
                map.initialZoom = true;
                map.fitBounds(bounds);


            });
        };

        // Function for adding a marker to the page.
        function addMarker(MapPos, MapID, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath) {
            var marker = new google.maps.Marker({
                position: MapPos,
                map: map,
                draggable: DragAble,
                animation: google.maps.Animation.DROP,
                title: MapTitle,
                icon: iconPath
            });

            if (iconPath != "../Google Maps/css/images/pin_green.png") {
                //Content structure of info Window for the Markers
                contentString = $('<div class="marker-info-win">' +
                '<div class="marker-inner-win"><span class="info-content">' +
                '<h1 class="marker-heading">' + MapTitle + '</h1>' +
                MapDesc +
                '</span><button name="edit-marker" class="edit-marker" title="Edit Marker">Edit Marker</button><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button>' +
                '</div></div>');
                editBtn = contentString.find('button.edit-marker')[0];
                removeBtn = contentString.find('button.remove-marker')[0];

                //add click listner to remove marker button
                google.maps.event.addDomListener(editBtn, "click", function (event) {
                    //call Edit_marker function to remove the marker from the map
                    editMarker(MapID, map, marker, infowindow, event);
                    //marker.setMap(null);
                });
            }
            else {
                //Content structure of info Window for the Markers
                var contentString = $('<div class="marker-info-win">' +
                '<div class="marker-inner-win"><span class="info-content">' +
                '<h1 class="marker-heading">' + MapTitle + '</h1>' +
                MapDesc +
                '</span><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button>' +
                '</div></div>');
                //Find save button in infoWindow
                saveBtn = contentString.find('button.save-marker')[0];
                removeBtn = contentString.find('button.remove-marker')[0];
            }
            //Create an infoWindow
            var infowindow = new google.maps.InfoWindow();
            //set the content of infoWindow
            infowindow.setContent(contentString[0]);
            //add click listner to remove marker button
            google.maps.event.addDomListener(removeBtn, "click", function (event) {
                //call remove_marker function to remove the marker from the map
                removeMarker(MapID, marker);
                //marker.setMap(null);
            });




            if (typeof saveBtn !== 'undefined') //continue only when save button is present
            {
                //add click listner to save marker button
                google.maps.event.addDomListener(saveBtn, "click", function (event) {
                    var mReplace = contentString.find('span.info-content'); //html to be replaced after success
                    //var mName = contentString.find('input.save-name')[0].value; //name input field value
                    //var mDesc = contentString.find('textarea.save-desc')[0].value; //description input field value
                    //var mType = contentString.find('select.save-type')[0].value; //type of marker

                    var nParent = $(event.target).parent();
                    //var mReplace = contentString.find('span.info-content'); //html to be replaced after success
                    var mName = $(nParent).find('.save-name').val(); //name input field value
                    var mDesc = $(nParent).find('.save-desc').val(); //description input field value
                    var mType = $(nParent).find('option:selected').text(); //type of marker



                    if (mName == '' || mDesc == '') {
                        alert("Please enter Name and Description!");
                    } else {
                        //call save_marker function and save the marker details
                        save_marker(marker, MapID, mName, mDesc, mType, mReplace, event, infowindow);

                    }
                });
            }

            //add click listner to save marker button
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.open(map, marker); // click on marker opens info window
            });

            if (InfoOpenDefault) //whether info window should be open by default
            {
                infowindow.open(map, marker);
            }

        }

        //############### Save Marker Function ##############
        function save_marker(Marker, MapID, mName, mAddress, mType, replaceWin, sEvent, inWindow) {
            //Save new marker using jQuery Ajax
            var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
            var myData = {
                id: MapID,
                name: mName,
                address: mAddress,
                latlang: mLatLang,
                type: mType
            }; //post variables

            console.log(replaceWin);
            $.ajax({
                type: "POST",
                url: 'http://www.familymap.somee.com/api/maps',
                data: myData,
                success: function (data) {
                    ////Content structure of info Window for the Markers
                    //var contentString = $('<div class="marker-info-win">' +
                    //'<div class="marker-inner-win"><span class="info-content">' +
                    //'<h1 class="marker-heading">' + $('.save-name').val() + '</h1><p>' +
                    //$('.save-desc').val() +
                    //'</p></span><div><button name="edit-marker" class="edit-marker" title="Edit Marker">Edit Marker</button></div>' +
                    //'</div></div>');

                    //Content structure of info Window for the Markers
                    var contentString = $('<div class="marker-info-win">' +
                    '<div class="marker-inner-win"><span class="info-content">' +
                    '<h1 class="marker-heading">' + mName + '</h1><p>' +
                    mAddress +
                    '</p></span>' +
                    '</div></div><button name="edit-marker" class="edit-marker" title="Edit Marker">Edit Marker</button>');

                    replaceWin.html(contentString); //replace info window with new html
                    Marker.setDraggable(false); //set marker to fixed
                    Marker.setIcon('../Google Maps/css/images/pin_blue.png'); //replace icon


                    //editBtn = contentString.find('button.edit-marker')[0];
                    editBtn = contentString[1];
                    //add click listner to remove marker button
                    google.maps.event.addDomListener(editBtn, "click", function (event) {
                        //call Edit_marker function to remove the marker from the map
                        editMarker(MapID, map, Marker, inWindow, event);
                        //marker.setMap(null);
                    });

                    //Dynamically updating the list item when new marker saved to database
                    $('#markers_list').append("<li tag='" + Marker.getPosition().toUrlValue() + "'>" + $('.marker-inner-win > .info-content > .marker-heading').text() + "</li>");
                    $('.lbjs-list').append("<div class='lbjs-item'  tag='" + Marker.getPosition().toUrlValue() + "'>" + $('.marker-inner-win > .info-content > .marker-heading').text() + "</div>");

                    $('.lbjs').remove();
                    Fill_Marker_List();

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(thrownError); //throw any errors
                }
            });
        }

        //############### Function to Get Marker(s) From Databse  ##############
        function loadMarker() {
            var Mapurl = "http://www.familymap.somee.com/api/maps";
            $.ajax({
                type: "GET",
                url: Mapurl,
                success: function (result) {
                    for (var i = 0; i < result.length ; i++) {
                        var m_id = result[i].id;
                        var name = result[i].name;
                        var address = '<p>' + result[i].address + '</p>';
                        var latlang = result[i].latlang.split(",");
                        var type = result[i].type;
                        var googlePoint = new google.maps.LatLng(parseFloat(latlang[0]), parseFloat(latlang[1]));

                        addMarker(googlePoint, m_id, name, address, false, false, false, "../Google Maps/css/images/pin_blue.png");
                        //############MARKRS LIST#############################
                        $('#markers_list').append("<li tag='" + result[i].latlang + "'>" + name + "</li>")
                    }


                    if (mapID == '') {
                        mapID = 1;
                    }
                    else {
                        mapID = Math.max.apply(Math, toObject(result));
                    }


                    Fill_Marker_List();
                    //######################################################
                },
                error: function (error) {
                    alert('error' + error);
                }

            });
        }

        function toObject(result) {
            var rv = new Array;
            for (var i = 0; i < result.length; ++i)
                rv[i] = result[i].id;
            return rv;
        }

        //############### Function to Remove Marker(s) From Databse  ##############
        function removeMarker(m_id, Marker) {
            var Mapurl = 'http://www.familymap.somee.com/api/maps/' + m_id;
            /* determine whether marker is draggable new markers are draggable and saved markers are fixed */
            if (Marker.getDraggable()) {
                Marker.setMap(null); //just remove new marker
            }
            else {
                //Remove saved marker from DB and map using jQuery Ajax
                var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
                var myData = { delFlag: 'true', latlang: mLatLang }; //post variables
                $.ajax({
                    type: "DELETE",
                    url: Mapurl,
                    data: myData,
                    success: function (data) {
                        Marker.setMap(null);
                        alert(data);
                        //  for(var i=0; i<$('#markers_list li').length; i++)
                        // {
                        // if (Marker.getPosition().toUrlValue() == $($('#markers_list li')[i]).attr('tag')) {
                        //$('.lbjs-item').filter(function () { return $.text([this]) === $($('#markers_list li')[i]).text(); }).remove();
                        $(".lbjs-item[tag='" + Marker.getPosition().toUrlValue() + "']").remove();
                        //$('#markers_list li').filter(function () { return $.text([this]) === $($('#markers_list li')[i]).text(); }).remove();
                        $("#markers_list li[tag='" + Marker.getPosition().toUrlValue() + "']").remove();
                        // }
                        //  }
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(thrownError); //throw any errors
                    }
                });
            }
        }

        //############### Function to Edit Marker(s) From Databse  ##############
        function editMarker(mid, map, marker, iWindow, e) {
            var mLatLang = marker.getPosition().toUrlValue(); //get marker position
            //Find remove button in infoWindow
            var removeBtn;

            var parent = $(e.target).parent().parent();
            var mName = $(parent).find("h1").text() //name input field value
            var mDesc = $(parent).find("p").text() //description input field value

            marker.setDraggable(true);
            marker.setIcon("../Google Maps/css/images/pin_green.png"); //replace icon

            var MapTitle = "Edit Marker";
            var EditForm = '<p><div class="marker-edit">' +
                      '<form action="null" method="POST" name="EditMarker" id="EditMarker">' +
                      '<label for="pName"><span>Place Name :</span><input type="text" name="pName" class="save-name" placeholder="Enter Title" value="' + mName + '" maxlength="40" /></label>' +
                      '<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc" placeholder="Enter Address" maxlength="150">' + mDesc + '</textarea></label>' +
                      '<label for="pType"><span>Type :</span> <select name="pType" class="save-type"><option value="modelTown">MODEL TOWN</option><option value="dha">DHA</option>' +
                      '<option value="gardenTown">Garden Town</option></select></label>' +
                      '</form>' +
                      '</div></p><button name="save-marker" class="save-marker">Save Changes</button>';

            //Content structure of info Window for the Markers
            var contentString = $('<div class="marker-info-win">' +
            '<div class="marker-inner-win"><span class="info-content">' +
            '<h1 class="marker-heading">' + MapTitle + '</h1><p>' +
            EditForm +
            '</p></span>' +
            '</div></div>');

            iWindow.setContent(contentString[0]);
            //$('.save-name').val(mName);
            //$('.save-desc').val(mDesc);
            //$($(e.target).parent()).find("h1").val("heello");

            var mType = contentString.find('select.save-type')[0].value; //type of marker



            var oldData = {
                name: mName,
                address: mDesc,
                latlang: mLatLang,
                type: mType
            }; //post variables

            //Find save button in infoWindow
            var saveBtn = contentString.find('button.save-marker')[0];

            if (typeof saveBtn !== 'undefined') //continue only when save button is present
            {
                //add click listner to save marker button
                google.maps.event.addDomListener(saveBtn, "click", function (event) {
                    var nParent = $(event.target).parent();
                    var nName = $(nParent).find('.save-name').val(); //name input field value
                    var nDesc = $(nParent).find('.save-desc').val(); //description input field value
                    var nType = $(nParent).find('option:selected').text(); //type of marker

                    var nReplace = contentString.find('span.info-content'); //html to be replaced after success
                    // var nName = contentString.find('input.save-name')[0].value; //name input field value
                    //var nDesc = contentString.find('textarea.save-desc')[0].value; //description input field value
                    //var nType = contentString.find('select.save-type')[0].value; //type of marker

                    if (nName == '' || nDesc == '') {
                        alert("Please enter Name and Description!");
                    }

                    else {
                        //call save_marker function and save the marker details



                        //Save new marker using jQuery Ajax
                        var nLatLang = marker.getPosition().toUrlValue(); //get marker position
                        var myData = {
                            name: nName,
                            address: nDesc,
                            //latlang: nLatLang +'&'+mLatLang,
                            latlang: nLatLang,
                            type: nType
                        }; //post variables

                        $.ajax({

                            type: 'PUT',
                            url: 'http://www.familymap.somee.com/api/maps/' + mid,
                            // dataType: 'json',
                            //contentType: 'application/json',
                            //data: JSON.stringify({ oData: oldData, nData: myData }),
                            data: myData,
                            success: function (data) {
                                alert(data);
                                if (nName != '' || nDesc != '') {
                                    //Content structure of info Window for the Markers

                                    var contentString = $('<div class="marker-info-win">' +
                                    '<div class="marker-inner-win"><span class="info-content">' +
                                    '<h1 class="marker-heading">' + nName + '</h1><p>' +
                                    nDesc + '</p></span><div><button name="edit-marker" class="edit-marker" title="Edit Marker">Edit Marker</button><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button><div>' +
                                    '</div></div>');
                                }
                                else {
                                    //Content structure of info Window for the Markers
                                    var contentString = $('<div class="marker-info-win">' +
                            '<div class="marker-inner-win"><span class="info-content">' +
                            '<h1 class="marker-heading">' + $('.save-name').val() + '</h1><p>' +
                            $('.save-desc').val() + '</p></span><div><button name="edit-marker" class="edit-marker" title="Edit Marker">Edit Marker</button><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button><div>' +
                            '</div></div>');
                                }

                                iWindow.setContent(contentString[0]); //replace info window with new html
                                marker.setDraggable(false); //set marker to fixed
                                marker.setIcon('../Google Maps/css/images/pin_blue.png'); //replace icon
                                editBtn = contentString.find('button.edit-marker')[0];


                                //add click listner to remove marker button
                                google.maps.event.addDomListener(editBtn, "click", function (event) {
                                    //call Edit_marker function to remove the marker from the map
                                    editMarker(mid, map, marker, iWindow, event);
                                    //marker.setMap(null);
                                });

                                //Dynamically updating the list item when new marker saved to database
                                //$('#markers_list').append("<li tag='" + marker.getPosition().toUrlValue() + "'>" + $('.marker-inner-win > .info-content > .marker-heading').text() + "</li>");
                                // $('.lbjs-list').append("<div class='lbjs-item'  tag='" + marker.getPosition().toUrlValue() + "'>" + $('.marker-inner-win > .info-content > .marker-heading').text() + "</div>");

                                $('.lbjs').remove();
                                Fill_Marker_List();

                                removeBtn = contentString.find('button.remove-marker')[0];
                                //add click listner to remove marker button
                                google.maps.event.addDomListener(removeBtn, "click", function (event) {
                                    //call remove_marker function to remove the marker from the map
                                    removeMarker(mid, marker);
                                    //marker.setMap(null);
                                });



                            },
                            error: function (xhr, ajaxOptions, thrownError) {
                                alert(thrownError); //throw any errors
                            }
                        });
                    }
                });

            }

        }



        //############### Fill Markers List  ##############
        function Fill_Marker_List() {
            $('#markers_list').listbox({ 'searchbar': true });
            //Mapping marker list with marker(s) div items and inserting attribute "tag" into the div
            for (i = 0; i < $('#markers_list li').length; i++) {
                $($('.lbjs-item')[i]).attr('tag', $($('#markers_list li')[i]).attr('tag'));
            }
            //Click event fired for saved items whenever page is refreshed and item is clicked
            $('.lbjs-list').on('click', 'div.lbjs-item', function (event) {
                //alert($(this).attr('value'));
                var latlang = $(this).attr('tag').split(",");

                var bounds = new google.maps.LatLngBounds();
                bounds.extend(new google.maps.LatLng(parseFloat(latlang[0]), parseFloat(latlang[1])));

                google.maps.event.addListener(map, 'zoom_changed', function () {
                    zoomChangeBoundsListener =
                        google.maps.event.addListenerOnce(map, 'bounds_changed', function (event) {
                            if (this.getZoom() > 15 && this.initialZoom == true) {
                                // Change max/min zoom here
                                this.setZoom(18);
                                this.initialZoom = false;
                            }
                            google.maps.event.removeListener(zoomChangeBoundsListener);
                        });
                });
                map.initialZoom = true;
                map.fitBounds(bounds);
            });


        }

    });

</script>
